<template>
  <Dialog
    class="slim-dialog"
    :title="t('studentHonor.view.title')"
    v-model="dialogVisible"
    width="1000"
  >
    <el-tabs v-model="activeName" type="border-card" tab-position="bottom">
      <el-tab-pane :label="t('studentHonor.view.tab1')" name="first">
        <template
          v-if="
            !edit &&
            type === 'edit' &&
            (formData.reviewStatus === '草稿' ||
              formData.reviewStatus === '已撤回' ||
              formData.reviewStatus === '已拒绝')
          "
        >
          <el-button
            class="mb-[16px]"
            type="primary"
            plain
            @click="handleEdit"
            :disabled="formLoading"
          >
            <Icon icon="ep:edit" />
            {{ t('studentHonor.view.clickEdit') }}
          </el-button>
        </template>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-position="top"
          label-width="120px"
          @submit.prevent
        >
          <el-descriptions v-loading="formLoading" :column="2" border label-width="150">
            <el-descriptions-item
              label-class-name="is--asterisk"
              :label="t('studentHonor.fields.honorName')"
              width="280"
              :span="2"
            >
              <el-form-item prop="honorName">
                <EditInput
                  v-model="formData.honorName"
                  :placeholder="
                    t('common.inputTextPlaceholder') + t('studentHonor.fields.honorName')
                  "
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="t('studentHonor.fields.honorTime')" width="280">
              <el-form-item prop="honorTime">
                <EditDate
                  v-model="formData.honorTime"
                  :placeholder="
                    t('common.inputTextPlaceholder') + t('studentHonor.fields.honorTime')
                  "
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="t('studentHonor.fields.honorType')" width="280">
              <el-form-item prop="honorType">
                <EditDict
                  :dict-type="DICT_TYPE.HONOR_TYPE"
                  v-model="formData.honorType"
                  :placeholder="
                    t('common.selectTextPlaceholder') + t('studentHonor.fields.honorType')
                  "
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="t('studentHonor.fields.teamHonor')" width="280">
              <el-form-item prop="teamHonor">
                <EditDict
                  :dict-type="DICT_TYPE.HONOR_TEAM_HONOR"
                  v-model="formData.teamHonor"
                  :placeholder="
                    t('common.selectTextPlaceholder') + t('studentHonor.fields.teamHonor')
                  "
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="t('studentHonor.fields.ranking')" width="280">
              <el-form-item prop="ranking">
                <EditDict
                  :dict-type="DICT_TYPE.HONOR_RANKING"
                  v-model="formData.ranking"
                  :placeholder="
                    t('common.selectTextPlaceholder') + t('studentHonor.fields.ranking')
                  "
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item
              :label="t('studentHonor.fields.attachment')"
              width="280"
              :span="2"
            >
              <el-form-item prop="attachment">
                <IMRUpload v-model="formData.attachment" :disabled="!edit" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="t('studentHonor.fields.remark')" width="280" :span="2">
              <el-form-item prop="remark">
                <EditInput
                  v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  :maxlength="200"
                  show-word-limit
                  :placeholder="t('common.inputTextPlaceholder') + t('studentHonor.fields.remark')"
                />
              </el-form-item>
            </el-descriptions-item>
            <template v-if="type === 'edit'">
              <el-descriptions-item :label="t('studentHonor.fields.reviewStatus')" width="280">
                <el-tag v-if="formData.reviewStatus" type="primary"
                  >{{ formData.reviewStatus }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item :label="t('studentHonor.fields.reviewerName')" width="280">
                <el-tag v-if="formData.reviewerName" type="primary"
                  >{{ formData.reviewerName }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item :label="t('studentHonor.fields.reviewTime')" width="280">
                {{ formatDate(formData.reviewTime) }}
              </el-descriptions-item>
              <el-descriptions-item :label="t('studentHonor.fields.reviewComments')" width="280">
                {{ formData.reviewComments }}
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="dataId" :label="t('studentHonor.view.tab2')" name="second">
        <StudentHonorArchive :data-id="dataId" />
      </el-tab-pane>
    </el-tabs>

    <template v-if="edit" #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="handleCancelClick">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StudentHonorApi, StudentHonorVO } from '@/api/core/studenthonor'
import EditInput from '@/components/EditViewInput/EditInput.vue'
import EditDate from '@/components/EditViewInput/EditDate.vue'
import EditDict from '@/components/EditViewInput/EditDict.vue'
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import IMRUpload from '@/components/IMRUpload/index.vue'
import { FormInstance } from 'element-plus'
import _ from 'lodash-es'
import StudentHonorArchive from './StudentHonorArchive.vue'

/** 荣誉奖项 表单 */
defineOptions({ name: 'StudentHonorForm' })

const edit = ref(false)
provide('editMode', edit)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<Partial<StudentHonorVO>>({})
const type = ref('edit')
const activeName = ref('first')
const formRef = ref<FormInstance>()

const formRules = reactive({
  honorName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentHonor.fields.honorName'),
      trigger: 'blur'
    }
  ]
})

const dataId = ref('')
/** 打开弹窗 */
const open = async (id?: string) => {
  formData.value = {}
  activeName.value = 'first'
  if (id) {
    dataId.value = id
    type.value = 'edit'
    // 修改
    edit.value = false
    dialogVisible.value = true
    formLoading.value = true
    formData.value = {}
    try {
      formData.value = await StudentHonorApi.getStudentHonor(id)
      if (formData.value && !formData.value?.attachment) {
        formData.value.attachment = '[]'
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    type.value = 'new'
    edit.value = true
    dialogVisible.value = true
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }
  if (type.value === 'edit') {
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentHonorVO
      await StudentHonorApi.updateStudentHonor(data)
      message.success(t('common.updateSuccess'))
      edit.value = false
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentHonorVO
      await StudentHonorApi.createStudentHonor(data)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
}

const backData = ref<Partial<StudentHonorVO>>({})

const handleEdit = () => {
  if (type.value === 'edit') {
    backData.value = _.cloneDeep(formData.value)
    edit.value = true
  }
}

const handleCancelClick = () => {
  if (type.value === 'edit') {
    edit.value = false
    formData.value = _.cloneDeep(backData.value)
    backData.value = {}
  } else {
    dialogVisible.value = false
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.is--asterisk) {
  &:after {
    content: '*';
    margin-left: 4px;
    color: var(--el-color-primary);
  }
}

:deep(.el-form-item__error) {
  top: 80%;
}
</style>
